package dongze.com.ckdj.ui;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.UploadImageDialogAdapter;
import dongze.com.ckdj.persistence.dao.State;
import dongze.com.ckdj.service.IImageUploadCallback;
import dongze.com.ckdj.service.IImageUploadService;
import dongze.com.ckdj.service.ImageUploadService;
import dongze.com.ckdj.service.ImageUploadTask;

/**
 * Created by fanqwz on 2017/10/12.
 */

public class ImageUploadDialog extends AlertDialog implements UploadImageDialogAdapter.OnTaskActionListener {
    IImageUploadService service;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ImageUploadDialog.this.service = IImageUploadService.Stub.asInterface(service);

            try {
                ImageUploadDialog.this.service.addCallback(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            startTasks();
            showProgressBar(false);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service = null;
            showProgressBar(true);
        }
    };

    Handler handler;
    CallBack callBack;

    IImageUploadCallback callback = new IImageUploadCallback.Stub() {
        @Override
        public void onTaskProgressChanged(final ImageUploadTask task, int progress) throws RemoteException {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.updateState(task.getId(), UploadImageDialogAdapter.STATE.STATE_UPLOAD);
                    adapter.updateProgress(task.getId(), task.getUploadProgress());
                }
            });
        }

        @Override
        public void onTaskFinished(final ImageUploadTask task) throws RemoteException {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null)
                        callBack.onTaskFinished(task);

                    adapter.updateState(task.getId(), UploadImageDialogAdapter.STATE.STATE_FINISHED);
                }
            });
        }

        @Override
        public void onTaskFailed(final ImageUploadTask task) throws RemoteException {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.updateState(task.getId(), UploadImageDialogAdapter.STATE.STATE_FAIL);
                }
            });
        }

        @Override
        public void onTaskAdded(final ImageUploadTask task) throws RemoteException {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.updateState(task.getId(), UploadImageDialogAdapter.STATE.STATE_WAITING);
                }
            });

        }

        @Override
        public void onTaskDeleted(ImageUploadTask task) throws RemoteException {

        }

        @Override
        public void onTaskCanceled(ImageUploadTask task) throws RemoteException {

        }

        @Override
        public void onNetStateChanged(int state) throws RemoteException {

        }
    };

    @BindView(R.id.list)
    ListView listView;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.ok)
    Button okBtn;
    @BindView(R.id.data_content)
    ViewGroup dataContent;

    private List<ImageUploadTask> tasks;
    private UploadImageDialogAdapter adapter;

    public ImageUploadDialog(Context context, List<ImageUploadTask> taskList, List<File> images, CallBack callBack) {
        super(context);
        this.callBack = callBack;
        setCancelable(false);
        tasks = taskList;
        adapter = new UploadImageDialogAdapter(taskList, images, this);
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_upload_image);
        ButterKnife.bind(this);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getContext().bindService(new Intent(getContext(), ImageUploadService.class), conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        listView.setAdapter(null);

        if (service != null) {
            try {
                service.removeCallback(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        getContext().unbindService(conn);
    }

    private void startTasks() {
        if (service != null && tasks != null) {
            for (ImageUploadTask ta :
                    tasks) {
                try {
                    service.addTask(ta);
                    service.setTaskForce(ta);
                    service.reStartTask(ta.getId());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void showProgressBar(final boolean show) {
        if (progressBar != null && dataContent != null) {
            progressBar.post(new Runnable() {
                @Override
                public void run() {
                    progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
                    dataContent.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
                }
            });
        }
    }

    @OnClick(R.id.ok)
    void onOkClick(Button button) {
        if (service != null) {
            for (ImageUploadTask t :
                    tasks) {
                try {
                    service.deleteTask(t.getId());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        dismiss();
    }

    @Override
    public void restartTask(long id) {
        if (service != null) {
            try {
                service.reStartTask(id);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void allFinished() {
        okBtn.setEnabled(true);

        if (callBack != null)
            callBack.onAllTaskFinished();
    }

    public interface CallBack {
        void onTaskFinished(ImageUploadTask task);
        void onAllTaskFinished();
    }
}
